﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ReportFlat.Common;
using ReportFlat.DataAccess;
using System.Collections;

namespace ReportFlat.Web.server.system
{
    public class Approve : BaseHandler
    {
        /// <summary>
        /// 获取审批数据
        /// </summary>
        [UseDB]
        public void GetApproveInfo()
        {
            int approveID = Convert.ToInt32(Request["approveID"]);
            int billID = Convert.ToInt32(Request["billID"]);
            int step = Convert.ToInt32(Request["step"]);
            //获取审批记录
            IList<t_approve_record> approveRecord = dao.GetList<t_approve_record>("FApproveID=" + approveID + " and FBillID=" + billID);
            //获取下一步审批人
            IList<t_user> approver = null;
            t_approve_detail nowStep = dao.Get<t_approve_detail>("FApproveID=" + approveID + " and FStep=" + step);
            if (nowStep != null)
            {
                if (string.IsNullOrEmpty(nowStep.FApprover))
                {
                    //1、填空则全选用户  
                    approver = dao.GetList<t_user>();
                }
                else if (nowStep.FApprover.StartsWith("user:"))
                {
                    //2、部分用户则用user:id,id2,id3形式
                    string ids = nowStep.FApprover.Substring(5);
                    approver = dao.GetList<t_user>(String.Format("FID in({0})", ids));
                }
                else if (nowStep.FApprover.StartsWith("role:"))
                {
                    //3、角色则用role:role1,role2,role3
                    string roles = nowStep.FApprover.Substring(5);
                    IList<t_roleuser> roleUsers = dao.GetList<t_roleuser>(String.Format("FRoleID in({0})", roles));
                    string ids = "";
                    foreach (var roleUser in roleUsers)
                    {
                        ids += (ids == "" ? "," : "") + roleUser.FID;
                    }
                    if (ids != "")
                    {
                        approver = dao.GetList<t_user>(String.Format("FID in({0})", ids));
                    }
                }
            }
            //获取审批配置信息
            IList<t_approve_detail> approvedetail = dao.GetList<t_approve_detail>("FApproveID=" + approveID);

            jsonResult = JSONHelper.AddF("approveRecord", approveRecord)
                                   .AddF("nowStep", nowStep)
                                   .AddF("approver", approver)
                                   .AddF("approveDetail", approvedetail).ToSucJson();

        }
       
        //审批通过
        [UseDB(Transaction = true)]
        public void ApprovePass()
        {
            //客户端提交时step+1
            t_approve_record obj = ToPo<t_approve_record>();
            obj.FApproverDate = DateTime.Now;
            obj.FApprover = GMLogin.User.FID;  //TODO:加FApproverID
            //保存审批记录
            dao.Save(obj);
            SendMessage(obj);
            //回写业务表
            t_approve approve = dao.Get<t_approve>(obj.FApproveID);
            t_approve_detail nowStep = dao.Get<t_approve_detail>("FApproveID=" + obj.FApproveID + " and FStep=" + obj.FStep);
            if (approve!=null && nowStep != null)
            {
                string sql = @"update {table} set FApproveStep={stepValue},FApproveStatus={statusValue},FToApprover={toApproverValue}
                                               {approverField} {datetimeField}
                               where FID={billID}";
                sql = sql.Replace("{table}", approve.FTable);
                sql = sql.Replace("{stepValue}", nowStep.FStep.ToString()); //(nowStep.FStep + (nowStep.FIsEnd?0:1)).ToString());
                sql = sql.Replace("{statusValue}", nowStep.FPassVal.ToString());
                sql = sql.Replace("{toApproverValue}", obj.FToApprover.ToString());
                if (string.IsNullOrEmpty(nowStep.FApproverField))
                {
                    sql = sql.Replace("{approverField}", "");
                }
                else
                {
                    sql = sql.Replace("{approverField}", "," + nowStep.FApproverField + "=" + GMLogin.UserID.ToString());
                }
                if (string.IsNullOrEmpty(nowStep.FDatetimeField))
                {
                    sql = sql.Replace("{datetimeField}", "");
                }
                else
                {
                    sql = sql.Replace("{datetimeField}", "," + nowStep.FDatetimeField + "=" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss").wrap());
                }
     
                sql = sql.Replace("{billID}", obj.FBillID.ToString());
                dao.ExcuteByHSql(sql);
            }
            jsonResult = JSONHelper.SuccessJson;
        }

        //审批打回
        [UseDB(Transaction = true)]
        public void ApproveBack()
        {
            t_approve_record obj = ToPo<t_approve_record>();
            obj.FApproverDate = DateTime.Now;
            obj.FApprover = GMLogin.UserID;  
            //取上一步审批记录
            string strwhere= "FBillID=" + obj.FBillID.ToString() + " and FStep=" + (obj.FStep-1).ToString();
            t_approve_record preRecord = dao.GetList<t_approve_record>(strwhere,"FID DESC")[0];
            //保存审批记录
            obj.FToApprover = preRecord.FApprover;
            dao.Save(obj);
            SendMessage(obj);
            //回写业务表
            t_approve approve = dao.Get<t_approve>(obj.FApproveID);
            t_approve_detail preStep = dao.Get<t_approve_detail>("FApproveID=" + obj.FApproveID + " and FStep=" + (obj.FStep-1));
            t_approve_detail nowStep = dao.Get<t_approve_detail>("FApproveID=" + obj.FApproveID + " and FStep=" + obj.FStep);
            if (approve != null && nowStep != null)
            {
                string sql = @"update {table} set FApproveStep={stepValue},FApproveStatus={statusValue},FToApprover={toApproverValue}
                                                 {approverField}{datetimeField}
                               where FID={billID}";
                sql = sql.Replace("{table}", approve.FTable);
                sql = sql.Replace("{stepValue}", (Convert.ToInt32(preStep.FStep)-1).ToString());
                sql = sql.Replace("{statusValue}", nowStep.FBackVal.ToString());
                sql = sql.Replace("{toApproverValue}", preRecord.FApprover.ToString());
                if (string.IsNullOrEmpty(preStep.FApproverField))
                { 
                    sql = sql.Replace("{approverField}", ""); 
                }
                else
                { 
                    sql = sql.Replace("{approverField}", ","+preStep.FApproverField+"=0"); 
                }
                if (string.IsNullOrEmpty(preStep.FDatetimeField))
                {
                    sql = sql.Replace("{datetimeField}", "");
                }
                else {
                    sql = sql.Replace("{datetimeField}", ","+preStep.FDatetimeField+"=null");
                }
               
                sql = sql.Replace("{billID}", obj.FBillID.ToString());
                dao.ExcuteByHSql(sql);
            }
            jsonResult = JSONHelper.SuccessJson;
        }



        private string SendMessage(t_approve_record obj)
        {
            if(obj.FApproveID==1) //采购申请
            {
                t_message message =  new t_message();
                message.FBillID = obj.FBillID;
                message.FBillType = "apply";
                message.FID=0;
                message.FReceiverID =obj.FToApprover;
                message.FReceiverName = obj.ToApproverName;
                message.FSendDate = obj.FApproverDate;
                message.FSenderID = obj.FApprover;
                message.FSenderName = obj.ApproverName;
                message.FStatus = 0;
                message.FTitle = "采购申请";
                c_apply apply = dao.Get<c_apply>(obj.FBillID);
                message.FDetail = apply.UserName+"的采购申请需要您的审核,快去看看吧！采购单编号:"+apply.FApplyNo;
                dao.Save(message);
            }
            else //发货申请
            {
                t_message message =  new t_message();
                message.FBillID = obj.FBillID;
                message.FBillType = "delivery";
                message.FID=0;
                message.FReceiverID =obj.FToApprover;
                message.FReceiverName = obj.ToApproverName;
                message.FSendDate = obj.FApproverDate;
                message.FSenderID = obj.FApprover;
                message.FSenderName = obj.ApproverName;
                message.FStatus = 0;
                message.FTitle = "发货申请";
                c_delivery apply = dao.Get<c_delivery>(obj.FBillID);
                message.FDetail = apply.UserName+"的发货申请需要您的审核,快去看看吧！";
                dao.Save(message);
            }
            return JSONHelper.SuccessJson;
        }
    }
}